
from subprocess import call
import sys,os,tempfile,shutil
debug=False
def debug_print(*args):
    if debug is True:print(*args,file=sys.stderr)
touch=lambda name:open(name,'a').close()
def wordtomarkdown(filename,tmp_dir=None,targetdir=None):
    suffix=['',".odt",".docx",".pdf",".doc"]

    base=os.path.basename(filename)
    for i in suffix:
        fname=filename+i
        if os.path.exists(fname):
            tmpdir=tempfile.TemporaryDirectory()
            try:
                html=tmpdir.name + '/' + base + '.html'
                cmd="unoconv -f html -o '%s' '%s'" % (html,fname)
                debug_print(cmd)
                call(cmd,shell=True)
                from .html2md import html2text

                with open(html,'r') as f:
                    s=html2text(f.read())
                if os.path.exists(targetdir) is False:
                    os.makedirs(targetdir)
                with open(targetdir + '/' + base + '.md','w') as f:
                    f.write("[TOC]\n\n")
                    f.write(s)
                if debug:
                    os.makedirs(os.path.join(tmpdir.name,'f','y'))
                    touch(os.path.join(tmpdir.name,'f','y','testfile'))
                for i in os.listdir(tmpdir.name):
                    f=os.path.join(tmpdir.name,i)
                    if f == html:
                        continue
                    if os.path.isdir(f):
                        shutil.copytree(f,os.path.join(targetdir,i))
                    else:
                        shutil.copy(f,os.path.join(targetdir,i))
                    debug_print(i)
                return True
            finally:
                tmpdir.cleanup()
    return False


if __name__ == '__main__':
    sys.path.insert(0,'..')
    from jywiki import utils
    utils.debug=True
    utils.wordtomarkdown(sys.argv[1],targetdir='test')


